import BuildForm from '@/components/BuildForm/BuildForm';
import FormattedMessageCustom from '@/components/FormattedMessageCustom/FormattedMessageCustom';
import { CONFIG } from '@/constants';
import { mapForm } from '@/pages/order/buildFormItems';
import { authName } from '@/servers/api/userController';
import { formFormat, getBase64Callback } from '@/utils';
import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import { getLocale, history, useIntl, useModel } from '@umijs/max';
import type { GetProp, UploadProps } from 'antd';
import { Button, Typography, Upload, message } from 'antd';

import { useEffect, useRef, useState } from 'react';
import { attract } from './attract';
type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0];
const AuthRealName: React.FC = () => {
    const intl = useIntl();
    const { initialState } = useModel('@@initialState');
    const { user, site } = initialState as IGlobal.IInitialState;
    const { Title, Text } = Typography;
    const lang = getLocale();
    const formItems = useRef();
    const [form, setForm] = useState();
    const [uploadDataList, setuploadDataList] = useState();
    const title = 'Особое внимание';
    const description =
        'Нажмите, чтобы начать запись видео, нацелиться на камеру, по запросу произнести следующий текст, Здравствуйте, я российский пользователь Иркутска, я хочу использовать GluZapp для покупки товаров в Китае, подать заявку на согласие';
    const [loading, setLoading] = useState(false);
    const [imageUrl, setImageUrl] = useState<string>();
    function onFinish(val: IBuildForm.IDefault) {
        const params = formFormat(val, formItems.current);
        const reg =
            /^((1[1-5])|(2[1-3])|(3[1-7])|(4[1-6])|(5[0-4])|(6[1-5])|[7-9]1)\d{4}(19|20|21)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
        if (lang === 'zh-CN') {
            if (!reg.test(params.idnum)) {
                message.error(intl.formatMessage({ id: '身份证号码错误' }));
                return;
            }
        }
        authName({
            ...params,
            video: uploadDataList,
        }).then((res) => {
            message.success(
                intl.formatMessage({ id: '提交成功，请等待后台审核' }),
            );
            history.back();
        }).catch(err=>{
            message.error(err.msg)
        })
    }
    const beforeUpload = (file: FileType) => {
        const isJpgOrPng =
            file.type === 'video/mp4' ||
            file.type === 'video/avi' ||
            file.type === 'video/wmv' ||
            file.type === 'video/mpeg';
        if (!isJpgOrPng) {
            message.error('You can only upload mp4/avi/wmv/mpeg file!');
        }
        const isLt2M = file.size / 1024 / 1024 < 10;
        if (!isLt2M) {
            message.error('Image must smaller than 10MB!');
        }
        return (isJpgOrPng && isLt2M) || Upload.LIST_IGNORE;
    };
    const handleChange: UploadProps['onChange'] = (info) => {
        if (info.file.status === 'uploading') {
            setLoading(true);
            return;
        }
        if (info.file.status === 'done') {
            setuploadDataList([info.file.response.data?.url])
            // Get this url from response in real world.
            getBase64Callback(info.file.originFileObj as FileType, (url) => {
                setLoading(false);
                setImageUrl(url);
            });
        }
    };
    useEffect(() => {
        if (user && site) {
            //验证是否为企业  ,site.identity_id 是个人类型,目前只有一个
            const isQy = user.identity_id !== site.identity_id;
            if (lang === 'zh-CN' && isQy) {
                formItems.current = attract[1];
                mapForm(formItems.current, 0).then((res) => {
                    setForm(res);
                });
            }
            if (lang === 'zh-CN' && !isQy) {
                formItems.current = attract[0];
                mapForm(formItems.current, 0).then((res) => {
                    setForm(res);
                });
            }
            if (lang === 'ru-RU') {
                formItems.current = attract[2];
                mapForm(formItems.current, 0).then((res) => {
                    setForm(res);
                });
            }
        }
    }, [user, site]);
    const uploadButton = (
        <button
            style={{
                border: '1px solid #ddd',
                background: 'none',
                borderRadius: 10,
                padding: '30px 40px',
                cursor: 'pointer',
                marginTop: 20,
                backgroundColor:'rgba(0,0,0,.03)'
            }}
            type="button"
        >
            {loading ? <LoadingOutlined /> : <PlusOutlined />}
            <div style={{ marginTop: 8 }}>Upload</div>
        </button>
    );
    return (
        <>
            {lang === 'ru-RU' && (
                <div style={{ textAlign: 'center' }}>
                    <Title level={5}>{title}</Title>
                    <Text>{description}</Text>
                    <br />
                    <Upload
                        beforeUpload={beforeUpload}
                        onChange={handleChange}
                        maxCount={1}
                        showUploadList={false}
                        action={CONFIG.HTTP_REQUEST_URL + '/common/upload'}
                    >
                        {imageUrl ? (
                            <video src={imageUrl} style={{ width: '200px',marginTop:30 }} />
                        ) : (
                            uploadButton
                        )}
                    </Upload>
                </div>
            )}
            <BuildForm
                formItems={formItems.current}
                value={form}
                onFinish={onFinish}
            >
                <Button type="primary" htmlType="submit">
                    <FormattedMessageCustom id="提交"></FormattedMessageCustom>
                </Button>
            </BuildForm>
        </>
    );
};
export default AuthRealName;
